# -*- coding: utf-8 -*-
import json
import logging
from typing import Dict, List, Any, Optional

# 确保日志配置正确
if not logging.getLogger().handlers:
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# 使用一个固定的logger名称，确保全局一致性
logger = logging.getLogger("modular_response_generator")
logger.setLevel(logging.INFO)  # 显式设置级别

# 确保logger有handler
if not logger.handlers:
    # 添加一个stream handler，直接输出到控制台
    handler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    handler.setLevel(logging.INFO)
    logger.addHandler(handler)
    logger.propagate = True  # 允许传播到父logger
# 导入模块化组件
from .patient_state_builder import PatientStateBuilder
from .fact_extractor import FactExtractor
from .neutral_response_generator import NeutralResponseGenerator
from .persona_rewriter import PersonaRewriter


class ModularResponseGenerator:
    """
    模块化回答生成器
    
    整合四个模块，实现"内容生成与人格表达解耦"的完整流程
    """
    
    def __init__(self, model_handler=None, config=None):
        """
        初始化模块化回答生成器
        
        Args:
            model_handler: 模型处理器
            config: 配置对象
        """
        self.model_handler = model_handler
        self.config = config
        
        # 初始化四个模块
        self.state_builder = PatientStateBuilder(config)
        self.fact_extractor = FactExtractor(config, model_handler)
        self.neutral_generator = NeutralResponseGenerator(model_handler, config)
        self.persona_rewriter = PersonaRewriter(model_handler, config)
        
        logger.info("模块化回答生成器初始化完成")
    
    def generate_response(self, data: Dict[str, Any]) -> str:
        """
        使用模块化方法生成患者回答
        
        Args:
            data: 包含患者信息、医生提问等的数据字典
            
        Returns:
            生成的患者回答
        """
        try:
            logger.info("开始模块化回答生成流程")
            
            # ① 患者状态构建模块
            #logger.info("步骤1: 构建患者状态")
            patient_state = self.state_builder.build_patient_state(data)
            logger.info(f"患者状态构建完成，信息完整度: {patient_state.get('PatientState', {}).get('系统状态', {}).get('信息完整度', 0)}")
            
            # ② 信息提取与一致性校验模块
            logger.info("步骤2: 提取和校验事实")
            facts = self.fact_extractor.extract_and_validate_facts(
                data["doctor_question"], patient_state
            )
            logger.info(f"事实提取完成，共 {facts.get('_meta', {}).get('total_facts', 0)} 个事实\nfacts:{facts}")
            
            # ③ 中性回答生成模块
            logger.info("步骤3: 生成中性回答")
            neutral_response = self.neutral_generator.generate_neutral_response(
                data["doctor_question"], facts
            )
            logger.info(f"中性回答生成完成: {neutral_response}")
            
            # ④ 人格化改写模块
            logger.info("步骤4: 人格化改写")
            persona_response = self.persona_rewriter.rewrite_with_persona(
                neutral_response, data["doctor_question"], data["人格"]
            )
            logger.info(f"人格化改写完成: {persona_response}")
            
            #logger.info("模块化回答生成流程完成")
            return persona_response
            
        except Exception as e:
            logger.error(f"模块化回答生成失败: {str(e)}")
            # 失败时返回默认回答
            return self._get_fallback_response(data)
    
    def generate_batch_responses(self, batch_data: List[Dict[str, Any]]) -> List[str]:
        """
        批量生成患者回答
        
        Args:
            batch_data: 批量数据列表
            
        Returns:
            生成的回答列表
        """
        responses = []
        
        try:
            logger.info(f"开始批量模块化回答生成，共 {len(batch_data)} 个请求")
            
            for i, data in enumerate(batch_data):
                logger.debug(f"处理第 {i+1}/{len(batch_data)} 个请求")
                
                try:
                    response = self.generate_response(data)
                    responses.append(response)
                except Exception as e:
                    logger.error(f"处理第 {i+1} 个请求失败: {str(e)}")
                    responses.append(self._get_fallback_response(data))
            
            logger.info(f"批量模块化回答生成完成，成功处理 {len(responses)} 个请求")
            return responses
            
        except Exception as e:
            logger.error(f"批量模块化回答生成失败: {str(e)}")
            # 返回默认回答列表
            return [self._get_fallback_response(data) for data in batch_data]
    
    def generate_response_with_intermediate_results(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        生成回答并返回中间结果（用于调试和分析）
        
        Args:
            data: 包含患者信息、医生提问等的数据字典
            
        Returns:
            包含最终回答和中间结果的字典
        """
        try:
            logger.info("开始模块化回答生成流程（包含中间结果）")
            
            intermediate_results = {}
            
            # ① 患者状态构建模块
            logger.debug("步骤1: 构建患者状态")
            patient_state = self.state_builder.build_patient_state(data)
            intermediate_results["patient_state"] = patient_state
            logger.debug(f"患者状态构建完成，信息完整度: {patient_state.get('PatientState', {}).get('系统状态', {}).get('信息完整度', 0)}")
            
            # ② 信息提取与一致性校验模块
            logger.debug("步骤2: 提取和校验事实")
            facts = self.fact_extractor.extract_and_validate_facts(
                data["doctor_question"], patient_state
            )
            intermediate_results["facts"] = facts
            logger.debug(f"事实提取完成，共 {facts.get('_meta', {}).get('total_facts', 0)} 个事实")
            
            # ③ 中性回答生成模块
            logger.debug("步骤3: 生成中性回答")
            neutral_response = self.neutral_generator.generate_neutral_response(
                data["doctor_question"], facts
            )
            intermediate_results["neutral_response"] = neutral_response
            logger.debug(f"中性回答生成完成: {neutral_response}")
            
            # ④ 人格化改写模块
            logger.debug("步骤4: 人格化改写")
            persona_response = self.persona_rewriter.rewrite_with_persona(
                neutral_response, data["doctor_question"], data["人格"]
            )
            intermediate_results["persona_response"] = persona_response
            logger.debug(f"人格化改写完成: {persona_response}")
            
            # 返回完整结果
            result = {
                "final_response": persona_response,
                "intermediate_results": intermediate_results,
                "success": True,
                "error": None
            }
            
            logger.info("模块化回答生成流程完成（包含中间结果）")
            return result
            
        except Exception as e:
            logger.error(f"模块化回答生成失败（包含中间结果）: {str(e)}")
            return {
                "final_response": self._get_fallback_response(data),
                "intermediate_results": {},
                "success": False,
                "error": str(e)
            }
    
    def _get_fallback_response(self, data: Dict[str, Any]) -> str:
        """
        获取回退回答
        
        Args:
            data: 数据字典
            
        Returns:
            回退回答
        """
        try:
            # 根据医生提问类型生成简单的回退回答
            doctor_question = data.get("doctor_question", "")
            
            if any(keyword in doctor_question for keyword in ["症状", "不舒服", "疼", "痛"]):
                return "我有点不舒服，但说不太清楚。"
            elif any(keyword in doctor_question for keyword in ["时间", "多久", "什么时候"]):
                return "有一段时间了，记不太清。"
            elif any(keyword in doctor_question for keyword in ["程度", "严重", "厉害"]):
                return "感觉有点严重，但我也说不准。"
            else:
                return "我有点不舒服，但说不太清楚。"
                
        except Exception as e:
            logger.warning(f"生成回退回答失败: {str(e)}")
            return "我有点不舒服，但说不太清楚。"
    
    def get_module_status(self) -> Dict[str, Any]:
        """
        获取各模块状态
        
        Returns:
            模块状态字典
        """
        try:
            status = {
                "state_builder": {
                    "status": "正常",
                    "description": "患者状态构建模块"
                },
                "fact_extractor": {
                    "status": "正常", 
                    "description": "信息提取与一致性校验模块"
                },
                "neutral_generator": {
                    "status": "正常",
                    "description": "中性回答生成模块"
                },
                "persona_rewriter": {
                    "status": "正常",
                    "description": "人格化改写模块"
                }
            }
            
            # 检查人格示例库状态
            try:
                persona_examples = self.persona_rewriter.persona_examples
                status["persona_rewriter"]["persona_examples_count"] = len(persona_examples)
                status["persona_rewriter"]["persona_types"] = list(persona_examples.keys())
            except Exception as e:
                status["persona_rewriter"]["persona_examples_error"] = str(e)
            
            # 检查模型处理器状态
            if self.model_handler:
                status["model_handler"] = {
                    "status": "已连接",
                    "description": "模型处理器"
                }
            else:
                status["model_handler"] = {
                    "status": "未连接",
                    "description": "模型处理器"
                }
            
            return status
            
        except Exception as e:
            logger.error(f"获取模块状态失败: {str(e)}")
            return {"error": str(e)}
    
    def validate_data(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        验证输入数据
        
        Args:
            data: 输入数据
            
        Returns:
            验证结果
        """
        validation_result = {
            "valid": True,
            "errors": [],
            "warnings": []
        }
        
        try:
            # 检查必需字段
            required_fields = ["doctor_question", "人格"]
            for field in required_fields:
                if field not in data:
                    validation_result["valid"] = False
                    validation_result["errors"].append(f"缺少必需字段: {field}")
            
            # 检查医生提问
            if "doctor_question" in data:
                doctor_question = data["doctor_question"]
                if not doctor_question or not doctor_question.strip():
                    validation_result["valid"] = False
                    validation_result["errors"].append("医生提问不能为空")
                elif len(doctor_question.strip()) < 3:
                    validation_result["warnings"].append("医生提问过短")
            
            # 检查人格信息
            if "人格" in data:
                persona = data["人格"]
                if not persona:
                    validation_result["warnings"].append("人格信息为空，将使用默认人格")
            
            # 检查患者信息
            patient_info_fields = ["基础信息", "门诊病历", "门诊对话"]
            missing_patient_info = []
            for field in patient_info_fields:
                if field not in data or not data[field]:
                    missing_patient_info.append(field)
            
            if missing_patient_info:
                validation_result["warnings"].append(f"缺少患者信息: {', '.join(missing_patient_info)}")
            
            return validation_result
            
        except Exception as e:
            logger.error(f"数据验证失败: {str(e)}")
            return {
                "valid": False,
                "errors": [f"验证过程出错: {str(e)}"],
                "warnings": []
            }
